package com.webserver.core;

import com.webserver.http.EmptyRequestException;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.http.httpContext;
import com.webserver.servlet.Change_Password;
import com.webserver.servlet.Login;
import com.webserver.servlet.register;

import java.io.*;
import java.net.Socket;

public class ClientHanlder implements Runnable{
    private Socket socket;
    private String path;
    public ClientHanlder(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            HttpRequest request = new HttpRequest(socket);
            HttpResponse response = new HttpResponse(socket);
            path=request.getRequestURI();
            if("/myweb/register".equals(path)) {
                register register = new register();
                register.server(request, response);
            }else if("/myweb/loginUser".equals(path)){
                Login login = new Login();
                login.server(request,response);
            }else if("/myweb/change_password".equals(path)){
                Change_Password changePassword = new Change_Password();
                changePassword.server(request,response);
            }else {
                File file = new File("./Webapps" + path);
                if (file.exists() && file.isFile()) {
                    response.setFile(file);
                } else {
                    response.setState("404 NotFound");
                    response.setFile(new File("./Webapps/myweb/404.html"));
                }
            }
            response.putHeader("Server","WebServer");
            response.flush();
        } catch (EmptyRequestException e) {
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
